<template>
    <z-block url="/do/get/mar_template" :params="params">
        <template #default="data">
            <z-form v-if="data" url="/do/patch/mar_template" :fields="['context']" :data="data"
                :beforeSubmit="beforeSubmit" >
                <template #context="formData">
                    <z-tiptap v-model="formData.context" style="margin-bottom: 20px" height="720px"
                        :plugins="plugins" @update:modelValue="update" />
                </template>
            </z-form>
        </template>
    </z-block>
</template>

<script>
import Contract from './blocks/contract/index';
import Material from './blocks/material/index';
function getElementsByType(elements, type, result = []) {
    for (let i = 0; i < elements.length; i++) {
        const element = elements[i];
        if (element.type === type) {
            result.push(element);
        } else if (element.content && element.content.length > 0) {
            getElementsByType(element.content, type, result)
        }
    }
    return result
}
export default {
    props: {
        params: Object,
    },
    data() {
        return {
            editor: null,
            plugins: [Contract, Material],
            fields: [],
        };
    },
    methods: {
        update(value, editor) {
            this.editor = editor
        },
        beforeSubmit(formData) {
            if (!this.editor) {
                return { field: formData.field, context: formData.context };
            }
            const meterialElements = getElementsByType(this.editor.getJSON().content, 'Material')
            const materialfield = meterialElements.map(({ attrs }) => ({ ...attrs }));
            const contractElements = getElementsByType(this.editor.getJSON().content, 'Contract')
            const contractfield = contractElements.map(({ attrs }) => ({ ...attrs }));
            this.fields = [...materialfield, ...contractfield]
            return { field: this.fields, context: formData.context }
        }
    },
}
</script>
